
/**
 * @Project : Clion_ProgrammingExercises
 * @File : 2841
 * @Author : WangRuoyu 
 * @Date : 2023/9/5 17:07
 */

#include "iostream"
#include "vector"
#include "unordered_map"

using namespace std;

class Solution {
public:
    long long maxSum(vector<int>& nums, int m, int k) {
        unordered_map<int, int> map;
        long long res = 0;
        long long sum = 0;
        int cnt = 0;
        int l = 0;
        for (int l = 0, r = 0; r < nums.size(); l++, r++) {
            sum += nums[r];
            if (map[nums[r]] == 0)cnt++;
            map[nums[r]]++;
            if (r - l + 1 < k) {
                l--;
            } else {
                if (cnt >= m) res = max(res, sum);
                sum -= nums[l];
                if (map[nums[l]] == 1)cnt--;
                map[nums[l]]--;
            }
        }
        return res;
    }
};

int main() {
    Solution sl;
    vector<int> nums = {2, 6, 7, 3, 1, 7};
    int m = 3;
    int k = 4;
    cout << sl.maxSum(nums, m, k);
    return 0;
}